import React from 'react';
import style from './style.styl';
import { findDOMNode } from 'react-dom';

import cx from 'classnames'; 
import util from '../../util';

class ScrollMenu extends React.Component {
  static contextTypes = {
    onContentScroll: React.PropTypes.func.isRequired,
  }
  constructor(props) {
    super(props);
    this.displayName = 'ScrollMenu';
    this.state = {
      scrollIndex: -1,
    }
  }
  onWheel = (e) => {
    const {
      scrollMenu,
      ...others,
    } = this.refs;
    const scrollTop = scrollMenu.getBoundingClientRect().top;
    let index = -1;
    for (const key in others) {
      const item = others[key];
      const dom = findDOMNode(item);
      const {
        offsetTop,
      } = dom;
      if(offsetTop + scrollTop < 260){
        index = item.props.index;
      }
    }
    this.setState({
      scrollIndex: index,
    });
  }
  shouldComponentUpdate(nextProps, nextState) {
    if(nextState.scrollIndex === this.state.scrollIndex && util.isShallowEqual(nextProps, this.props)) return false;
    else return true;
  }
  onScrollTop = (i) => {
    const item = this.refs[`ref_${i}`];
    const dom = findDOMNode(item);
    const {
      offsetTop,
    } = dom;
    this.context.onContentScroll(offsetTop);
    this.setState({
      scrollIndex: i
    });
  }
  render() {
    const {
      scrollIndex,
    } = this.state;
    const menus = [];
    const items = React.Children.map(this.props.children, (child, i) => {
      if(!child) return child;
      const {
        title
      } = child.props;
      const {
        props
      } = child;
      if(props.name === 'ScrollTitle')
        menus.push({
          type: props.name,
          title,
          list: []
        });
      else
        menus[menus.length - 1].list.push({
          type: props.name,
          title,
          index: i,
        });
      return React.cloneElement(child,{
        ref: `ref_${i}`,
        index: i,
      });
    });
    return (
      <div className={style['root']} ref={'scrollMenu'} onWheel={this.onWheel}>
        <div className={style['menu']}>
          {
            menus.map((v, i) => {
              return (
                <div className={style['menu-title']} key={i}>
                  <span>{v.title}</span>
                  <div className={style['menu-lists']}>
                    {
                      v.list.map((sv, si) => {
                        return <div className={cx({
                          [style['menu-text']]: true,
                          [style['active']]: sv.index === scrollIndex || (!i && !si && !~scrollIndex),
                        })} key={si} onClick={this.onScrollTop.bind(this, sv.index)}>{sv.title}</div>
                      })
                    }
                  </div>
                </div>
              );
            })
          }
        </div>
        <div className={style['area']}>
          {items}
        </div>
      </div>
    );
  }
}

export default ScrollMenu;
